/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.socket.xml;

import java.io.IOException;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
 *
 * @author CongChinh
 */
public class XMLParser {
            /*
             String xmlString;
             xmlString  = openTag("query");
             xmlString +=   newItem("action","ADD");
             xmlString +=   openTag("data");
             xmlString +=       openTag("motor");
             xmlString +=           newItem("id","MU");
             xmlString +=           newItem("name","Mio Ultimo");
             xmlString +=           newItem("color","Trang");
             xmlString +=           newItem("price","30");
             xmlString +=           newItem("mark","YAM");
             xmlString +=           newItem("quantity","5");
             xmlString +=       closeTag("motor");
             xmlString +=   closeTag("data");
             xmlString += closeTag("query");
             */
    private Document doc;	
    public XMLParser()
    {
        doc = null;            
    }
    //
    public String getValue(String tagName) {
        return doc.getElementsByTagName(tagName).item(0).getTextContent();     
    }
    public String getValue(String tagName, int index) {
        return doc.getElementsByTagName(tagName).item(index).getTextContent();     
    }
    //
    public void parserXMLString(String xmlString) throws SAXException, IOException, ParserConfigurationException
    {
        DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
        doc = docBuilder.parse(new InputSource(new StringReader(xmlString)));
        //doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader(xmlString)));
    }
    //
    public String openTag(String tag) {
        return "<"+tag+">";
    }
    public String closeTag(String tag) {
        return "</"+tag+">";
    }
    public String newItem(String tag, String content) {
        return "<"+tag+">" + content + "</"+tag+">";
    }
}             
